<template>
  <el-card shadow style="height: 100%;width: 100%;">
    <div slot="header" class="clearfix">
      <!-- <span>
        <el-tag type="success">已授权</el-tag>
        <el-tag type="danger">未授权</el-tag>
      </span> -->
      <el-button
        type="primary"
        icon="el-icon-circle-check"
        @click="saveRoleGrant"
      >保存</el-button>
    </div>
    <!-- <v-org-tree
      v-for="tree in permissionTree"
      :key="tree.id"
      :data="tree"
      :node-render="nodeRender"
      :horizontal="true"
      @on-node-click="handleNodeClick"
    /> -->
    <el-tree
      ref="tree"
      :data="permissionTree"
      highlight-current
      :expand-on-click-node="false"
      show-checkbox
      node-key="id"
      :check-strictly="true"
      :default-expanded-keys="defaultExpandedKeys"
      :default-checked-keys="defaultCheckedKeys"
      :props="defaultProps"
      @check="clickDeal"
    />
  </el-card>
</template>
<script>
import { grant, revoke, saveAuth, findAuthPermissionTree } from '@/api/admin/role';

export default {
  name: 'AuthPermission',
  props: {
    roleId: {
      type: String,
      required: true
    },
    type: {
      type: Number,
      required: true
    }
  },
  data() {
    return {
      permissionTree: [],
      defaultCheckedKeys: [],
      defaultExpandedKeys: [],
      zoom: 100,
      defaultProps: {
        children: 'children',
        label: 'label',
        key: 'id'
      }
    };
  },
  updated() {
    this.$refs.tree.setCheckedKeys(this.defaultCheckedKeys);
  },
  mounted: function() {
    this.$nextTick(() => {
      this.initTree();
    });
  },
  methods: {
    clickDeal(currentObj, treeStatus) {
      const selected = treeStatus.checkedKeys.indexOf(currentObj.id);
      if (selected !== -1) {
        this.selectedParent(currentObj);
        this.uniteChildSame(currentObj, true);
      } else {
        if (currentObj.children.length !== 0) {
          this.uniteChildSame(currentObj, false);
        }
      }
    },
    uniteChildSame(treeList, isSelected) {
      this.$refs.tree.setChecked(treeList.id, isSelected);
      for (let i = 0; i < treeList.children.length; i++) {
        this.uniteChildSame(treeList.children[i], isSelected);
      }
    },
    // 统一处理父节点为选中
    selectedParent(currentObj) {
      const currentNode = this.$refs.tree.getNode(currentObj);
      if (currentNode.parent.key !== undefined) {
        this.$refs.tree.setChecked(currentNode.parent, true);
        this.selectedParent(currentNode.parent);
      }
    },
    initTree() {
      const params = {
        roleId: this.roleId,
        type: this.type
      };
      findAuthPermissionTree(params).then(response => {
        const result = response.data;
        if (result.code === 0) {
          this.defaultCheckedKeys = [];
          this.defaultExpandedKeys = [];
          this.permissionTree = result.data;
          this.getCheckedKey(result.data);
        } else {
          this.$notify.error({
            title: result.code,
            message: result.msg
          });
        }
      });
    },
    auth(data) {
      const params = {
        roleId: this.roleId,
        relType: 0,
        relId: data.id
      };
      if (!data.checked) {
        grant(params).then(response => {
          const result = response.data;
          if (result.code === 0) {
            this.$notify({
              title: '成功',
              message: '授权成功',
              type: 'success'
            });
            this.initTree();
          } else {
            this.$notify.error({
              title: result.code,
              message: result.msg
            });
          }
        });
      } else {
        revoke(params).then(response => {
          const result = response.data;
          if (result.code === 0) {
            this.$notify({
              title: '成功',
              message: '撤销授权成功',
              type: 'success'
            });
            this.initTree();
          } else {
            this.$notify.error({
              title: result.code,
              message: result.msg
            });
          }
        });
      }
    },
    nodeRender(h, data) {
      const color = data.checked === true ? 'success' : 'danger';
      return (
        <el-tag type={color}>{data.label}</el-tag>
      );
    },
    handleNodeClick(e, data, expand) {
      this.auth(data);
    },
    saveRoleGrant() {
      const params = {
        roleId: this.roleId,
        relType: 0,
        relId: this.$refs.tree.getCheckedKeys()[0],
        relIds: this.$refs.tree.getCheckedKeys().join(','),
        type: this.type
      };
      saveAuth(params).then(response => {
        const result = response.data;
        if (result.code === 0) {
          this.$notify({
            title: '成功',
            message: '授权成功',
            type: 'success'
          });
          this.initTree();
        } else {
          this.$notify.error({
            title: result.code,
            message: result.msg
          });
        }
      });
    },
    getCheckedKey(treeData) {
      treeData.forEach(element => {
        if (element.checked) {
          this.defaultCheckedKeys.push(element.id);
          if (element.expand) {
            this.defaultExpandedKeys.push(element.id);
          }
          if (element.children !== null) {
            this.getCheckedKey(element.children);
          }
        }
      });
    }
  }
};
</script>
